/**
 * WebRTC SDP 处理工具
 * 提供 SDP 验证、修改等功能
 */

export interface SdpValidationResult {
  isValid: boolean;
  hasBundle: boolean;
  hasAudio: boolean;
  hasVideo: boolean;
  hasIceCandidate: boolean;
  hasIceUfrag: boolean;
  hasIcePwd: boolean;
  hasFingerprint: boolean;
  candidateCount: number;
  candidates: string[];
  errors: string[];
  warnings: string[];
}

/**
 * 验证 SDP 格式
 */
export const validateSdp = (sdp: string): SdpValidationResult => {
  const result: SdpValidationResult = {
    isValid: true,
    hasBundle: sdp.includes('a=group:BUNDLE'),
    hasAudio: sdp.includes('m=audio'),
    hasVideo: sdp.includes('m=video'),
    hasIceCandidate: sdp.includes('a=candidate:'),
    hasIceUfrag: sdp.includes('a=ice-ufrag:'),
    hasIcePwd: sdp.includes('a=ice-pwd:'),
    hasFingerprint: sdp.includes('a=fingerprint:'),
    candidateCount: 0,
    candidates: [],
    errors: [],
    warnings: [],
  };

  // 提取 ICE 候选
  const candidateLines = sdp.split('\r\n').filter(line => line.startsWith('a=candidate:'));
  result.candidateCount = candidateLines.length;
  result.candidates = candidateLines;

  // 验证基本要求
  if (sdp.length < 100) {
    result.isValid = false;
    result.errors.push('SDP 格式无效或太短');
  }

  if (!result.hasAudio && !result.hasVideo) {
    result.isValid = false;
    result.errors.push('SDP 必须包含至少一个媒体流（音频或视频）');
  }

  // SRS 6.0 要求 BUNDLE
  if (!result.hasBundle) {
    result.warnings.push('SDP 缺少 BUNDLE 策略（SRS 6.0 要求）');
  }

  if (!result.hasIceCandidate) {
    result.warnings.push('SDP 中未找到 ICE 候选，连接可能失败');
  }

  return result;
};

/**
 * 确保 SDP 包含 BUNDLE 和 mid 字段
 */
export const ensureBundleAndMid = (sdp: string): { sdp: string; modified: boolean } => {
  const lines = sdp.split('\r\n');
  let modified = false;
  let mids: string[] = [];

  // 查找所有媒体行并确保它们有 mid
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    if (line.startsWith('m=audio') || line.startsWith('m=video')) {
      // 查找这个媒体块的 mid
      let mid: string | null = null;
      for (let j = i + 1; j < lines.length && !lines[j].startsWith('m='); j++) {
        if (lines[j].startsWith('a=mid:')) {
          mid = lines[j].substring(6);
          break;
        }
      }

      // 如果没有 mid，添加一个
      if (!mid) {
        const midValue = mids.length.toString();
        mids.push(midValue);
        // 在媒体行后插入 mid
        lines.splice(i + 1, 0, `a=mid:${midValue}`);
        modified = true;
      } else {
        mids.push(mid);
      }
    }
  }

  // 确保有 BUNDLE group
  if (!sdp.includes('a=group:BUNDLE')) {
    // 在 t=0 0 或 a=msid-semantic 之后添加
    let insertIndex = lines.findIndex(line => line.startsWith('a=msid-semantic:'));
    if (insertIndex < 0) {
      insertIndex = lines.findIndex(line => line.startsWith('t=0 0'));
    }
    if (insertIndex >= 0) {
      const bundleLine = mids.length > 0 ? `a=group:BUNDLE ${mids.join(' ')}` : 'a=group:BUNDLE 0';
      lines.splice(insertIndex + 1, 0, bundleLine);
      modified = true;
    }
  }

  return {
    sdp: modified ? lines.join('\r\n') : sdp,
    modified,
  };
};

/**
 * 提取 SRS 返回的 ICE 候选
 */
export const extractIceCandidates = (sdp: string): string[] => {
  return sdp.split('\r\n').filter(line => line.startsWith('a=candidate:'));
};

